import 'package:flutter/material.dart';
import 'package:slwl/pages/404.dart';
import 'package:slwl/pages/login/index.dart';
import 'package:slwl/pages/setting/index.dart';
import 'package:slwl/pages/tab_bar/index.dart';
import 'package:slwl/utils/token.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await TokenManager().init();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // 全局路由守卫
      onGenerateRoute: (settings) {
        TokenManager tokenManager = TokenManager();
        String token = tokenManager.getToken();
        // 未登录，且不是登录页，跳转到登录页
        if (token.isEmpty && settings.name != '/login') {
          return MaterialPageRoute(builder: (context) => const LoginPage());
        }
        // 已登录，且是登录页，跳转到首页
        if (token.isNotEmpty && settings.name == '/login') {
          return MaterialPageRoute(builder: (context) => const TabBarPage());
        }

        if (settings.name == '/') {
          return MaterialPageRoute(builder: (context) => const TabBarPage());
        }

        if (settings.name == '/setting') {
          return MaterialPageRoute(builder: (context) => const SettingPage());
        }

        return MaterialPageRoute(builder: (context) => const NotFound());
      },
    );
  }
}
